using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml.XPath;
using System.Xml;

namespace InstaladorAlternativo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
            ExecuteFile("ldifde", "-m -f  arquivo.ldf");
               //ExecuteFile("ldifde", "-f \"arquivo.ldf\" -r \"(&(objectClass=top)(&(objectClass=domain)(objectClass=domaindns)))\" -l \"dn\"");
            string dn = ReadFile("arquivo.ldf");
            ldap_p2.Text = "Cn=Users," + dn;            
               //ldap_p1.Text = Environment.MachineName.ToLower()+"."+dn.Replace(",DC=", ".").Substring(3);
            
        }

        public static void DirectoryCopy(string sourcePath, string destinationPath)
        {
            DirectoryInfo sourceDirectory = new DirectoryInfo(sourcePath);
            DirectoryInfo destinationDirectory = new DirectoryInfo(destinationPath);
            if (destinationDirectory.Exists == false)
            {
                destinationDirectory.Create();
                destinationDirectory.Attributes = sourceDirectory.Attributes;
            }

            foreach (FileInfo fileInfo in sourceDirectory.GetFiles())
            {
                fileInfo.CopyTo(destinationDirectory.FullName + @"\" + fileInfo.Name, true);
            }

            foreach (System.IO.DirectoryInfo directoryInfo in sourceDirectory.GetDirectories())
            {
                DirectoryCopy(directoryInfo.FullName, destinationDirectory.FullName + @"\" + directoryInfo.Name);
            }
        }


        static void ExecuteFile(string FileName, string arguments)
        {
            System.Diagnostics.Process p = System.Diagnostics.Process.Start(FileName, arguments);
            p.WaitForExit();
            //return;
        }

        private string ReadFile(string FileName)
        {
            StreamReader re = File.OpenText(FileName);
            string input = null;
            re.ReadLine();
            input = re.ReadLine();
            Regex regex = new Regex("^dn: .*$");
            input = regex.Match(input).ToString();
            input = input.Replace("dn: ", null);
            re.Close();
            re.Dispose();

            re = File.OpenText(FileName);
            string input2 = null;
            do
            {
                input2 = re.ReadLine();
                Regex regex2 = new Regex("^dNSHostName: .*$");
                input2 = regex2.Match(input2).ToString();
                if (!input2.Equals(""))
                    break;
            } while (input2 != null);
            input2 = input2.Replace("dn: ", null);

            re.Close();
            re.Dispose();
            
            ldap_p1.Text = input2.Replace("dNSHostName: ", "");

            return input;
        }

        private bool AlterConfigFile(string sDir)
        {            
            XmlTextReader reader = new XmlTextReader(sDir);            
            XmlDocument doc = new XmlDocument();
            doc.Load(reader); 
            reader.Close();            
            XmlNode Nodes = doc.SelectSingleNode("//appSettings");
            using (XmlWriter xw = Nodes.CreateNavigator().AppendChild())
            {
                xw.WriteStartElement("add");
                xw.WriteAttributeString("key", "AdPass");
                xw.WriteAttributeString("value", ad_password.Text);
                xw.WriteEndElement();

                xw.WriteStartElement("add");
                xw.WriteAttributeString("key", "AdUser");
                xw.WriteAttributeString("value", ad_login.Text);
                xw.WriteEndElement();

                xw.WriteStartElement("add");
                xw.WriteAttributeString("key", "ldapPath1");
                xw.WriteAttributeString("value", ldap_p1.Text);
                xw.WriteEndElement();

                xw.WriteStartElement("add");
                xw.WriteAttributeString("key", "ldapPath2");
                xw.WriteAttributeString("value", ldap_p2.Text);
                xw.WriteEndElement();

                xw.WriteStartElement("add");
                xw.WriteAttributeString("key", "MoodleUser");
                xw.WriteAttributeString("value", moodle_login.Text);
                xw.WriteEndElement();

                xw.WriteStartElement("add");
                xw.WriteAttributeString("key", "MoodlePass");
                xw.WriteAttributeString("value", moodle_password.Text);
                xw.WriteEndElement();

                xw.WriteStartElement("add");
                xw.WriteAttributeString("key", "MSUWS");
                xw.WriteAttributeString("value", msu_webservice_url.Text + @"\Login.asmx");
                xw.WriteEndElement();

                /*
                xw.WriteStartElement("MSU_UserControls.Properties.Settings");
                  xw.WriteStartElement("setting");
                    xw.WriteAttributeString("name", "MSU_UserControls_WSUserData_ChangeData");
                    xw.WriteAttributeString("serializeAs", "String");
                      xw.WriteStartElement("value");
                      xw.WriteString(msu_webservice_url.Text + @"/ChangeData.asmx");
                      xw.WriteEndElement();
                  xw.WriteEndElement();

                  xw.WriteStartElement("setting");
                    xw.WriteAttributeString("name", "MSU_UserControls_WSLogin_Login");
                    xw.WriteAttributeString("serializeAs", "String");
                      xw.WriteStartElement("value");
                      xw.WriteString(msu_webservice_url.Text + @"/Login.asmx");
                      xw.WriteEndElement();
                  xw.WriteEndElement();

                  xw.WriteStartElement("setting");
                    xw.WriteAttributeString("name", "MSU_UserControls_WSMSU_WSMSU");
                    xw.WriteAttributeString("serializeAs", "String");
                      xw.WriteStartElement("value");
                      xw.WriteString(msu_webservice_url.Text+@"/Login.asmx");
                      xw.WriteEndElement();
                  xw.WriteEndElement();
                xw.WriteEndElement();
                */
            }

            
            XmlNode Nodes2 = doc.SelectSingleNode("//SharePoint//SafeControls");
            using (XmlWriter xw = Nodes2.CreateNavigator().AppendChild())
            {
                xw.WriteStartElement("SafeControl");
                xw.WriteAttributeString("Assembly", "MSU_UserControls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7033bbd5189174c2");
                xw.WriteAttributeString("Namespace", "MSU_UserControls");
                xw.WriteAttributeString("TypeName", "MSU_WebParts");
                xw.WriteAttributeString("Safe", "True");
            }

            XmlNode Nodes3 = doc.SelectSingleNode("//system.web//httpModules");
            using (XmlWriter xw = Nodes3.CreateNavigator().AppendChild())
            {
                xw.WriteStartElement("add");
                xw.WriteAttributeString("name", "Session");
                xw.WriteAttributeString("type", "System.Web.SessionState.SessionStateModule");

            }

            //doc.Save(sDir);
            doc.Save(sDir);
            return true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
           
            if (msu_webservice_url.Text.Trim() == "")
            {
                MessageBox.Show("Complete the MSU Webservice URL");
                return;
            }
            if (ad_login.Text.Trim() == "")
            {
                MessageBox.Show("Complete the Administrator Login");
                return;
            }
            if (moodle_login.Text.Trim() == "")
            {
                MessageBox.Show("Complete the Administrator Moodle Login");
                return;
            }
            if (ldap_p1.Text.Trim() == "")
            {
                MessageBox.Show("You are not in a domain, can't install");
                return;
            }
            if (ldap_p2.Text.Trim() == "")
            {
                MessageBox.Show("You are not in a domain, can't install");
                return;
            }
            
            button1.Enabled = false;

            try
            {
                //Descubrir Diretorio TODO
                
                //string path = @"C:\Inetpub\wwwroot\wss\VirtualDirectories\80\UserControls";
                string path = sp_path.Text+@"\";
                string cur_dir = Directory.GetCurrentDirectory();
                
                AlterConfigFile(path + @"web.config");                
                DirectoryCopy(cur_dir + @"\UserControls\", path + @"\UserControls\");                
                DirectoryCopy(cur_dir + @"\bin\", path + @"\bin\");
                ExecuteFile(cur_dir + @"\gacutil.exe", @"/i "+path+@"\bin\"+"MSU_UserControls.dll");
                //ExecuteFile("iisreset");
                ExecuteFile("iisreset", @"/noforce");
                MessageBox.Show("WebParts install completed \n Installer will be close");
                Application.Exit();
            }
            catch (Exception error)
            {
                button1.Enabled = true;
                MessageBox.Show("Install failed try again! "+e.ToString());
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            DialogResult select_dir = folderBrowserDialog1.ShowDialog();
            sp_path.Text = folderBrowserDialog1.SelectedPath;
            //MessageBox.Show(folderBrowserDialog1.SelectedPath);
        }

    }
}